from app.db.mongoClient import ErrMongoClient, get_mongo_client
from . import dbSynPosBill, collectionBillList
from datetime import datetime
from app.globals.publicMethod import globalTimeToString

def query(startTime, endTime, stallNo, deviceNo, billState, payType, startPage, pageSize):
    '''
    订单流水查询
    '''
    try:
        mg_client = get_mongo_client()
        start = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
        end = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
        # 1000表示全部
        if 1000 == billState and 1000 == payType:
            cond = {'skj130OrderTime':{'$gte': start, '$lte': end}, 'deviceNo': deviceNo, 'stallNo': stallNo}
        elif 1000 == billState and 1000 != payType:
            cond = {'skj130OrderTime':{'$gte': start, '$lte': end}, 'deviceNo': deviceNo, 'payType': payType, 'stallNo': stallNo}
        elif 1000 != billState and 1000 == payType:
            cond = {'skj130OrderTime':{'$gte': start, '$lte': end}, 'deviceNo': deviceNo, 'billState': billState, 'stallNo': stallNo}
        else:
            cond = {'skj130OrderTime':{'$gte': start, '$lte': end}, 'deviceNo': deviceNo, 'payType': payType, 'billState': billState, 'stallNo': stallNo}

        collection = mg_client[dbSynPosBill][collectionBillList]
        totalCount = collection.find(cond).count()
        res = collection.find(cond).sort('skj130OrderTime', -1)
        if res is None:
            return {}
     
        orderList = []
        for v in res:
            order = {
                'billId': v.get('billId'),
                'device_no': v.get('deviceNo'),
                'thirdOrderNo': v.get('thirdOrderNo'),
                'skj130OrderTime': globalTimeToString(v.get('skj130OrderTime')),
                'appLocalOrderId': v.get('appLocalOrderId'),
                'skj130GatewayNo': v.get('skj130GatewayNo'),
                'skj130PosNo': v.get('skj130PosNo'),
                'orderAmount': v.get('orderAmount'),
                'chargeAmount': v.get('chargeAmount'),
                'cardQrCodeNum': v.get('cardQrCodeNum'),
                'createTime': globalTimeToString(v.get('createTime')),
                'bill_state': v.get('billState'),
                'pay_type': v.get('payType'),
                'bill_type': v.get('billType'),
                'dishList': v.get('dishList'),
                'operator': v.get('operator')
            }
            orderList.append(order)


        totalCount = int(len(orderList))
        totalPages = int((totalCount + pageSize) / pageSize)
        if len(orderList) == 0:
            totalPages = 0

        orderList_page = orderList[(startPage-1)*pageSize:(startPage-1)*pageSize+pageSize]
            
        data = {
            'totalPages': totalPages,
            'totalCount': totalCount,
            'currentPage': startPage,
            'orderList': orderList_page
        }
        return data
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def query_details(thirdOrderNo, deviceNo):
    '''
    根据流水号查询订单详情
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'thirdOrderNo': thirdOrderNo, 'deviceNo': deviceNo}
        v = mg_client[dbSynPosBill][collectionBillList].find_one(cond)
        data = {}
        if v is None:
            return data

        data = {
            'billId': v.get('billId'),
            'device_no': v.get('deviceNo'),
            'thirdOrderNo': v.get('thirdOrderNo'),
            'skj130OrderTime': globalTimeToString(v.get('skj130OrderTime')),
            'appLocalOrderId': v.get('appLocalOrderId'),
            'skj130GatewayNo': v.get('skj130GatewayNo'),
            'skj130PosNo': v.get('skj130PosNo'),
            'orderAmount': v.get('orderAmount'),
            'chargeAmount': v.get('chargeAmount'),
            'cardQrCodeNum': v.get('cardQrCodeNum'),
            'createTime': globalTimeToString(v.get('createTime')),
            'bill_state': v.get('billState'),
            'pay_type': v.get('payType'),
            'bill_type': v.get('billType'),
            'dishList': v.get('dishList'),
            'operator': v.get('operator')
        }

        return data 
    except Exception as e:
        raise ErrMongoClient.data(str(e))